<?php
/**
 * Author: xx.com
 */ 
namespace Shop\Controller;
use Common\Util\dada\api\AddOrderApi;
use Common\Util\dada\client\DadaRequestClient;
use Common\Util\dada\api\CityCodeApi;
use Common\Util\dada\api\ShopAddApi;
use Common\Util\JuheExp;
use Think\Controller;
use Think\Page;

class OrderController extends BaseController {

    /**
     * 析构流函数
     */
    public function  __construct() {   
        parent::__construct();    
        //$this->userLogic = new \Home\Logic\UsersLogic();
    }

    /**
     *  订单列表
     */
    public function order_list(){

        $p = I('p', 1, 'intval');
        $pagesize = I('pagesize', 10, 'intval');

        $order_status = I('order_status', 0, 'intval');
        $order_sn = I('order_sn', '', 'trim');
        $where['ord.shop_id'] = $this->shop_info['shop_id'];
        if($order_sn){
            $where['ord.order_sn'] = array('like', '%'.$order_sn.'%');
        }
        $where['ord.pay_status'] = 1;
        $order = 'ord.add_time DESC';
        switch($order_status){
            case 0 :  ;break;
            case 1 :  $where['ord.order_status'] = 0; break;    //未接单，待确认
            case 2 :  $where['ord.order_status'] = 1;$where['ord.shipping_status'] = 0;break;
            case 3 :  $where['ord.shipping_status'] = 1;$where['ord.order_status'] = array('not in', array(2,4));break;
            case 4 :  $where['ord.is_drawback'] = 1;$order='ord.drawback_time DESC';break;
            default:;break;
        }
        $orderModel = M('order');
        $count =  $orderModel->alias('ord')
            //->join('ln_drawback dra on ord.order_id = dra.order_id', 'left')
            ->where($where)->count();

        $field = array('ord.order_id', 'ord.order_sn', 'ord.order_status', 'ord.shipping_status', 'ord.pay_status',
                'ord.order_amount', 'ord.total_amount', 'ord.add_time', 'ord.total_buy_number', 'ord.pay_code', 'ord.is_drawback',
                'ord.shipping_code','ord.shipping_name', 'ord.goods_price', 'ord.shipping_price', 'ord.receiver_lng', 'ord.receiver_lat',
                'ord.order_type',            //'dra.money', 'dra.real_money', 'dra.status as drawback_status'
        );
        $order_list = $orderModel->alias('ord')
            ->field($field)
            //->join('ln_drawback dra on ord.order_id = dra.order_id', 'left')
            ->where($where)
            ->order($order)
            ->page($p, $pagesize)
            ->select();

        //$goodsModel = M('goods');
        $orderGoodsModel = M('order_goods');
        $drawbackModel = M('drawback');
        foreach($order_list as $key => &$val){
            $order_goods = $orderGoodsModel->alias('og')
                ->join('ln_goods as goods ON og.goods_id = goods.goods_id', 'left')
                ->field('og.rec_id, og.goods_num, og.member_goods_price,  og.apply_return, og.goods_price,    
                    goods.goods_id, goods.goods_name, goods.goods_remark, goods.original_img, goods.market_price')
                ->where(array('og.order_id'=>$val['order_id']))
                ->select();
            $amount_drawback = 0;
            foreach($order_goods as &$val2){
                $val2['original_img'] = parseMediaUrl($val2['original_img']);

                $val2['drawback_str'] = $val2['apply_return'] == 0 ? '' : ($val2['apply_return'] == 1 ? '待退款' : '已处理');
                if($val2['apply_return'] == 1){
                    $val2['drawback_btn'] = 1;
                    $amount_drawback = bcadd($amount_drawback, bcmul($val2['member_goods_price'], $val2['goods_num'], 2), 2);
                }else{
                    $val2['drawback_btn'] = 0;
                }
            }

            $amount_exp_fee = 0;
            $real_money = 0;
            $drawback_list = $drawbackModel->where(array('order_id'=>$val['order_id'], 'status'=>0))->select();
            foreach($drawback_list as $val_drawback){
                $amount_exp_fee = bcadd($amount_exp_fee, $val_drawback['exp_fee'], 2);
                $real_money = bcadd($real_money, $val_drawback['real_money'], 2);
            }

            $money_amount = bcsub($amount_drawback, $amount_exp_fee, 2);
            $val['real_money'] = $val['is_drawback'] == 1 ? ($money_amount > 0 ? $money_amount : 0) : ($val['is_drawback'] == 2 ? $real_money : 0) ;
            $val['goods_list'] = $order_goods;
            $val['order_status_desc'] = shopOrderStatusDesc(0, $val);
            $val['order_btn'] = shopOrderBtn(0, $val);
            /*if($val['drawback_status'] === null){
                $val['money'] = 0;
                $val['real_money'] = 0;
                $val['drawback_status'] = -1;
            }else if($val['drawback_status'] == 0){
                $val['real_money'] = $val['money'];
            }*/

        }
        $page_info = array('count'=>$count, 'page_count'=>count($order_list), 'p'=>I('p',1,'intval'), 'page_size'=>$pagesize);
        $this->returnInfo(1, '订单列表',  array('page_info'=>$page_info, 'list'=>$order_list));
    }

    /**
     * 订单详情
     */
    public function order_info(){
        $order_id = I('order_id', 0, 'intval');
        $orderModel = M('order');
        $where =array('order_id'=>$order_id, 'shop_id'=>$this->shop_info['shop_id']);

        $order_info = $orderModel->where($where)->find();
        $orderGoodsModel = M('order_goods');
        $goodsModel = M('goods');
        if($order_info){
            $order_info['add_time'] = date('Y-m-d H:i', $order_info['add_time']);
            $order_info['shipping_time'] = $order_info['shipping_time'] ? date('Y-m-d H:i', $order_info['shipping_time']) : '';
            $order_goods = $orderGoodsModel->alias('og')
                ->field('og.rec_id, og.goods_id, og.goods_num, og.member_goods_price, og.goods_price, og.apply_return,
                    goods.market_price, goods.goods_name, goods.goods_remark, goods.original_img')
                ->join('ln_goods as goods ON og.goods_id = goods.goods_id', 'left')
                ->where(array('og.order_id'=>$order_info['order_id']))
                ->select();
            foreach($order_goods as &$val2){
                $val2['original_img'] = parseMediaUrl($val2['original_img']);
                //$val2['drawback_btn'] = $val2['apply_return'] == 1 ? 1 : 0;
                $val2['drawback_str'] = $val2['apply_return'] == 0 ? '' : ($val2['apply_return'] == 1 ? '待退款' : '已处理');
            }
            $order_info['goods_list'] = $order_goods;
            $order_info['order_status_desc'] = shopOrderStatusDesc(0, $order_info);
            $order_info['order_btn'] = shopOrderBtn(0, $order_info);
            $drawback_info = M('drawback')->where(array('order_id'=>$order_id))->find();
            if($drawback_info){
                $drawback_info['create_time'] = date('Y-m-d H:i', $drawback_info['create_time']);
                $drawback_info['img'] = unserialize($drawback_info['img']);
                if(!empty($drawback_info['img']))
                {
                    foreach($drawback_info['img'] as &$item)
                    {
                        $item = parseMediaUrl($item);
                    }
                }else{
                    $drawback_info['img'] = [];
                }
                $drawback_info['update_time'] = $drawback_info['update_time'] ? date('Y-m-d H:i', $drawback_info['update_time']):'';
                //$drawback_info['auto_time_show'] = $drawback_info['auto_time'] ? date('Y-m-d H:i', $drawback_info['auto_time']):'';
            }
            $order_info['drawback_info'] = $drawback_info ;

            $this->returnInfo(1, '订单信息',  $order_info);
        }else{
            $this->returnInfo(0, '订单信息有误');
        }
    }

    /**
     * 确认接单
     */
    public function confirm_order(){
        $order_id = I('order_id', 0, 'intval');
        $orderModel = M('order');
        $where =array('order_id'=>$order_id, 'shop_id'=>$this->shop_info['shop_id']);
        $order_info = $orderModel->where($where)->find();
        if($order_info){
            if($order_info['order_status'] == 0){
                $updata['order_status'] = 1;
                $is_success_order = $orderModel->where($where)->save($updata);
                $is_success_action = $this->orderActionLog($order_id,'商家接单');
                if($is_success_order !== false && $is_success_action){
                    $this->returnInfo(1, '操作成功');
                }else{
                    $this->returnInfo(0, '操作失败');
                }

            }else{
                $this->returnInfo(0, '订单状态异常');
            }
        }else{
            $this->returnInfo(0, '订单信息有误');
        }
    }

    /*
     * 查询物流信息
     */
    public function get_express_info(){
        $order_id = I('order_id', 0, 'intval');
        $order_info = M('order')->field('order_sn, shipping_status, shipping_code')->where(array('order_id'=>$order_id))->find();
        if($order_info['shipping_status'] == 0){
            $this->returnInfo(0, '暂无物流信息');
        }

        $result = getExpByJuhe($order_id);
        $this->returnInfo($result['status'], $result['msg'], $result['result']);
    }

    /*
     * 查询物流信息
     */
    public function get_express_info_dada(){
        $order_id = I('order_id', 0, 'intval');
        $order_info = M('order')->field('order_sn, shipping_status, shipping_code')->where(array('order_id'=>$order_id))->find();
        if($order_info['shipping_status'] == 0){
            $this->returnInfo(0, '暂无物流信息');
        }
        if($order_info['shipping_code'] == 'dada'){
            $app_key = tpCache('shopping.dd_app_key');
            $app_secret = tpCache('shopping.dd_app_secret');
            $source_id = tpCache('shopping.dd_source_id');
            $is_test_dada = tpCache('shopping.dd_is_test');
            if(!$app_key || !$app_secret ||!$source_id){
                $this->returnInfo(0, '系统参数异常');
            }

            $config['app_key'] = $app_key;
            $config['app_secret'] = $app_secret;
            $config['v'] = '1.0';
            $config['format'] = 'json';
            $config['source_id'] = $is_test_dada == 1 ? '73753' : $source_id;
            $config['host'] = 'http://newopen.qa.imdada.cn';

            $data['order_id'] = $order_info['order_sn'];
            $send_data['url'] = "/api/order/status/query";
            $send_data['businessParams'] = json_encode($data);

            $dada_client = new DadaRequestClient($config, $send_data);
            $resp = $dada_client->makeRequest();
            $resp = object_array($resp, true);
            if($resp['status'] == 'success'){
                $this->returnInfo(1, '物流信息', $resp['result']);
            }else{
                $this->returnInfo(0, $resp['msg'], $resp['code']);
            }
        }else{

            $this->returnInfo(0, '暂无物流信息');
        }

    }

    /*
     * 订单操作记录
     */
    public function orderActionLog($order_id,$action,$note=''){
        $order = M('order')->where(array('order_id'=>$order_id))->find();
        $data['order_id'] = $order_id;
        $data['action_user'] = $this->user_id;
        $data['action_note'] = $note;
        $data['order_status'] = $order['order_status'];
        $data['pay_status'] = $order['pay_status'];
        $data['shipping_status'] = $order['shipping_status'];
        $data['log_time'] = time();
        $data['status_desc'] = $action;
        return M('order_action')->add($data);//订单操作记录
    }

    /**
     * 快递列表
     */
    public function get_express_list(){
        $list = M("plugin")->field('code, name')->where(['type' => 'shipping'])->select();
        $this->returnInfo(1, '快递列表', $list);
    }

    /**
     * 普通快递发货
     */
    public function send_express(){
        $order_id = I('order_id', 0, 'intval');
        $order = M('order')->where(array('order_id'=>$order_id))->find();
        if(!$order){
            $this->returnInfo(0, '订单信息有误');
        }

        $selectgoods = I('rec_id', '', 'trim');
        if($selectgoods){
            $selectgoods = explode(',', $selectgoods);
            $where_goods['rec_id'] = array('in', $selectgoods);
        }
        $where_goods['order_id'] = $order_id;
        $orderGoods = M('order_goods')->where($where_goods)->select();
        $selectgoods  = $selectgoods ? $selectgoods : get_arr_column($orderGoods, 'rec_id');

        $shipping_code = I('shipping_code');
        $shipping = M('plugin')->where(array('code'=>$shipping_code))->find();
        if(!$shipping){
            $this->returnInfo(0, '快递公司信息有误');
        }
        $invoice_no = I('invoice_no', '', 'trim');
        if(!$invoice_no){
            $this->returnInfo(0, '请填写快递单号');
        }
        $data['order_id'] = $order_id;
        $data['order_sn'] = $order['order_sn'];
        $data['zipcode'] = $order['zipcode'];
        $data['user_id'] = $order['user_id'];
        $data['admin_id'] = $this->user_id;
        $data['consignee'] = $order['consignee'];
        $data['mobile'] = $order['mobile'];
        $data['country'] = $order['country'];
        $data['province'] = $order['province'];
        $data['city'] = $order['city'];
        $data['district'] = $order['district'];
        $data['address'] = $order['address'];
        $data['shipping_code'] = $shipping_code;
        $data['shipping_name'] = $shipping['name'];
        $data['shipping_price'] = $order['shipping_price'];
        $data['create_time'] = time();
        $did = M('delivery_doc')->add($data);
        $is_delivery = 0;
        foreach ($orderGoods as $k=>$v){
            if($v['is_send'] == 1){
                $is_delivery++;
            }
            if($v['is_send'] == 0 && in_array($v['rec_id'],$selectgoods)){
                $res['is_send'] = 1;
                $res['delivery_id'] = $did;

                $r = M('order_goods')->where("rec_id=".$v['rec_id'])->save($res);//改变订单商品发货状态
                $is_delivery++;
            }
        }
        $updata['shipping_time'] = time();
        if($is_delivery == count($orderGoods)){
            $updata['shipping_status'] = 1;
        }else{
            $updata['shipping_status'] = 2;
        }
        $updata['shipping_code'] = $shipping_code;
        $updata['shipping_name'] = $shipping['name'];
        $is_success_order = M('order')->where("order_id=".$data['order_id'])->save($updata);//改变订单状态
        $s = $this->orderActionLog($order['order_id'],'delivery');//操作日志
        if($r !== false && $is_success_order !== false && $s){
            $this->returnInfo(1, '操作成功');
        }else{
            $this->returnInfo(0, '操作失败');
        }
    }

    /**
     * 达达发货
     */
    public function send_dada(){

        $app_key = tpCache('shopping.dd_app_key');
        $app_secret = tpCache('shopping.dd_app_secret');
        $source_id = tpCache('shopping.dd_source_id');
        $is_test_dada= tpCache('shopping.dd_is_test');

        if(!$app_key || !$app_secret ||!$source_id){
            $this->returnInfo(0, '系统参数异常');
        }

        $order_id = I('order_id', 0, 'intval');
        $order_info = M('order')->where(array('order_id'=>$order_id))->find();

        if(!$order_info){
            $this->returnInfo(0, '订单信息有误');
        }
        if($order_info['order_status'] == 0){
            $this->returnInfo(0, '请先接单');
        }
        $config['app_key'] = $app_key;
        $config['app_secret'] = $app_secret;
        $config['v'] = '1.0';
        $config['format'] = 'json';
        $config['source_id'] = $is_test_dada == 1 ? '73753' : $source_id;
        $config['host'] = $is_test_dada == 1 ?  'http://newopen.qa.imdada.cn' : "https://newopen.imdada.cn";
        $shop_info = M('shop')->where(array('id'=>$order_info['shop_id']))->find();
        //无门店数据
        $origin_shop_id = $shop_info['origin_shop_id'];

        if(!$origin_shop_id){
            //注册门店
            $origin_shop_id = 'xmtdd_'.date('ymd').'_'.$shop_info['id'];
            $dd_shop_info['station_name'] = $shop_info['shop_name'];
            $dd_shop_info['business'] = 13;
            $dd_shop_info['city_name'] = $shop_info['city_name'] ?$shop_info['city_name'] : '北京市';
            $dd_shop_info['area_name'] = $shop_info['area_name']?$shop_info['area_name'] : '东城区';
            $dd_shop_info['station_address'] = $shop_info['shop_address_street'] ? $shop_info['shop_address_street'] : '区驻地';
            $dd_shop_info['lng'] = $shop_info['longitude'];
            $dd_shop_info['lat'] = $shop_info['latitude'];
            $dd_shop_info['contact_name'] = $shop_info['shop_user'];
            $dd_shop_info['phone'] = $shop_info['shop_tel'];
            $dd_shop_info['origin_shop_id'] = $origin_shop_id;
            $shopList[] = $dd_shop_info;

            $shopAddApi['url'] = "/api/shop/add";
            $shopAddApi['businessParams'] = json_encode($shopList);

            $dada_client = new DadaRequestClient($config, $shopAddApi);
            $resp = $dada_client->makeRequest();
            $resp = object_array($resp);
            if($resp['status'] == 'success'){
                M('shop')->where(array('id'=>$order_info['shop_id']))->setField('origin_shop_id', $origin_shop_id);
            }else{
                $this->returnInfo(0, '门店注册失败：'.$resp['msg']);
            }
        }
        $region_list = get_region_list();
        $receiver_address = $region_list[$order_info['province']]['name'].$region_list[$order_info['city']]['name'].
            $region_list[$order_info['district']]['name'].$order_info['address'];

        $city_code = I('city_code', '', 'trim');
        if(!$city_code){
            $this->returnInfo(0, '未传递城市code');
        }
        $orderModel['shop_no'] = $origin_shop_id;	// 第三方门店编号
        $orderModel['origin_id'] = $order_info['order_sn'];			// 第三方订单号
        $orderModel['city_code'] =$city_code ;						// 城市code(可以参照城市code接口)
        $orderModel['cargo_price'] = $order_info['order_amount'];
        $orderModel['is_prepay'] = 0;
        $orderModel['receiver_name'] = $order_info['consignee'];
        $orderModel['receiver_address'] = $receiver_address;
        $orderModel['receiver_lat'] = $order_info['receiver_lat'];
        $orderModel['receiver_lng'] = $order_info['receiver_lng'];
        $orderModel['receiver_phone'] = $order_info['mobile'];
        $orderModel['callback'] = parseMediaUrl('/index.php/Shop/Order/dd_callback');							// 回调url, 每次订单状态变更会通知该url(参照回调接口)

//*********************3.实例化一个api*************************
        $addOrderApi = new AddOrderApi(json_encode($orderModel));
        $addOrderData['url'] = "/api/order/addOrder";
        $addOrderData['businessParams'] = json_encode($orderModel);

//***********************4.实例化客户端请求************************

        $dada_client = new DadaRequestClient($config, $addOrderData);
        $resp = $dada_client->makeRequest();
        $resp = object_array($resp);
        if($resp['status'] == 'success'){
            $update['shipping_code'] = 'dada';
            $update['shipping_status'] = 1;
            $update['shipping_time'] = time();

            M('order')->where(array('order_id'=>$order_id))->save($update);
            $this->orderActionLog($order_id,'商家发货');
            $this->returnInfo(1, $resp['msg'], $resp['result']);
        }else{
            $this->returnInfo(0, $resp['msg'], $resp['code']);
        }
    }

    /*
     * 达达订单运费
     */
    public function dada_qrery_fee(){
        $order_id = I('order_id', 0, 'intval');
        $order_info = M('order')->where(array('order_id'=>$order_id))->find();

        if(!$order_info){
            $this->returnInfo(0, '订单信息有误');
        }
        if($order_info['order_status'] == 0){
            $this->returnInfo(0, '请先接单');
        }

        $city_code = I('city_code', '010', 'trim');
        if(!$city_code){
            $this->returnInfo(0, '未传递城市code');
        }
        $result = $this->query_fee_detail($order_info, $city_code);
        if($result['status'] == 1){
            $update['shipping_price_real'] = $result['result']['fee'];
            $update['exp_fee_rate'] = tpCache('shopping.dd_exp_fee_rate');
            $is_success = M('order')->where(array('order_id'=>$order_id))->save($update);
            if($is_success === false){
                $this->returnInfo(0, '操作失败', $result['msg']);
            }
            $this->returnInfo(1, '操作成功', $result['result']);
        }
        $this->returnInfo(0, $result['msg']);
    }

    /*
     * 达达查询订单运费后发单
     */
    public function dada_after_qrery(){
        $order_id = I('order_id', 0, 'intval');
        $order_info = M('order')->where(array('order_id'=>$order_id))->find();

        if(!$order_info){
            $this->returnInfo(0, '订单信息有误');
        }
        if($order_info['order_status'] == 0){
            $this->returnInfo(0, '请先接单');
        }
        $deliveryNo = I('deliveryNo', '', 'trim');  //通过查询接口获取的达达单号
        $result = $this->after_query_detail($order_info, $deliveryNo);
        if($result['status'] == 1){
            $update['shipping_code'] = 'dada';
            $update['shipping_status'] = 1;
            $update['shipping_time'] = time();

            M('order')->where(array('order_id'=>$order_id))->save($update);
            $this->orderActionLog($order_id,'商家发货');
            $this->returnInfo(1, '成功');
        }
        $this->returnInfo(0, '失败');

    }

    /**
     * 查询价格具体方法
     * @param null $order_info
     * @param string $city_code
     */
    private function query_fee_detail($order_info=null, $city_code = '',$is_return = 0){

        $app_key = tpCache('shopping.dd_app_key');
        $app_secret = tpCache('shopping.dd_app_secret');
        $source_id = tpCache('shopping.dd_source_id');
        $is_test_dada= tpCache('shopping.dd_is_test');

        if(!$app_key || !$app_secret ||!$source_id){
            return array('status'=>0, 'msg'=>'系统参数异常', 'result'=>'');
            //$this->returnInfo(0, '系统参数异常');
        }

        $config['app_key'] = $app_key;
        $config['app_secret'] = $app_secret;
        $config['v'] = '1.0';
        $config['format'] = 'json';
        $config['source_id'] = $is_test_dada == 1 ? '73753' : $source_id;
        $config['host'] = $is_test_dada == 1 ?  'http://newopen.qa.imdada.cn' : "https://newopen.imdada.cn";
        $region_list = get_region_list();
        //发货店铺信息
        $shop_info = M('shop')->where(array('id'=>$order_info['shop_id']))->find();
        $city_code = $city_code ? $city_code : $shop_info['city_code'];
        if($is_return == 0){
            //店铺正常下单
            $origin_shop_id = $shop_info['origin_shop_id'];
            //无门店数据
            if(!$origin_shop_id){
                //注册门店
                $origin_shop_id = 'xmtdd_'.date('ymd').'_'.$shop_info['id'];
                $dd_shop_info['station_name'] = $shop_info['shop_name'];
                $dd_shop_info['business'] = 13;
                $dd_shop_info['city_name'] = $shop_info['city_name'] ?$shop_info['city_name'] : '北京市';
                $dd_shop_info['area_name'] = $shop_info['area_name']?$shop_info['area_name'] : '东城区';
                $dd_shop_info['station_address'] = $shop_info['shop_address_street'] ? $shop_info['shop_address_street'] : '区驻地';
                $dd_shop_info['lng'] = $shop_info['longitude'];
                $dd_shop_info['lat'] = $shop_info['latitude'];
                $dd_shop_info['contact_name'] = $shop_info['shop_user'];
                $dd_shop_info['phone'] = $shop_info['shop_tel'];
                $dd_shop_info['origin_shop_id'] = $origin_shop_id;
                $shopList[] = $dd_shop_info;

                $shopAddApi['url'] = "/api/shop/add";
                $shopAddApi['businessParams'] = json_encode($shopList);

                $dada_client = new DadaRequestClient($config, $shopAddApi);
                $resp = $dada_client->makeRequest();
                $resp = object_array($resp);
                if($resp['status'] == 'success'){
                    M('shop')->where(array('id'=>$order_info['shop_id']))->setField('origin_shop_id', $origin_shop_id);
                }else{
                    return array('status'=>0, 'msg'=>'门店注册失败：'.$resp['msg'], 'result'=>'');
                    //$this->returnInfo(0, '门店注册失败：'.$resp['msg']);
                }
            }

            $receiver_address = $region_list[$order_info['province']]['name'].$region_list[$order_info['city']]['name'].
                $region_list[$order_info['district']]['name'].$order_info['address'];

            $receiver_name = $order_info['consignee'];
            $receiver_lat = $order_info['receiver_lat'];
            $receiver_lng = $order_info['receiver_lng'];
            $receiver_phone = $order_info['mobile'];
            $order_sn = $order_info['order_sn'];
        }else{
            //用户退货  默认退货店铺 id = 6
            $shop_info_return = M('shop')->where(array('id'=>6))->find();
            $origin_shop_id = $shop_info_return['origin_shop_id'];
            if(!$origin_shop_id){
                //注册门店
                $origin_shop_id = 'xmtdd_'.date('ymd').'_'.$shop_info['id'];
                $dd_shop_info['station_name'] = $shop_info_return['shop_name'];
                $dd_shop_info['business'] = 13;
                $dd_shop_info['city_name'] = $region_list[$order_info['city']]['name'] ? $region_list[$order_info['city']]['name'] : '北京市';
                $dd_shop_info['area_name'] = $region_list[$order_info['district']]['name']?$region_list[$order_info['district']]['name'] : '东城区';
                $dd_shop_info['station_address'] = $order_info['address'] ? $order_info['address'] : '区驻地';
                $dd_shop_info['lng'] = $order_info['receiver_lng'];
                $dd_shop_info['lat'] = $order_info['receiver_lat'];
                $dd_shop_info['contact_name'] = $order_info['consignee'];
                $dd_shop_info['phone'] = $order_info['mobile'];
                $dd_shop_info['origin_shop_id'] = $origin_shop_id;
                $shopList[] = $dd_shop_info;

                $shopAddApi['url'] = "/api/shop/add";
                $shopAddApi['businessParams'] = json_encode($shopList);

                $dada_client = new DadaRequestClient($config, $shopAddApi);
                $resp = $dada_client->makeRequest();
                $resp = object_array($resp);
                if($resp['status'] == 'success'){
                    M('shop')->where(array('id'=>6))->setField('origin_shop_id', $origin_shop_id);
                }else{
                    return array('status'=>0, 'msg'=>'门店注册失败：'.$resp['msg'], 'result'=>'');
                    //$this->returnInfo(0, '门店注册失败：'.$resp['msg']);
                }
            }else{
                //更新门店数据
                $shop_up['origin_shop_id'] = $origin_shop_id;
                $shop_up['city_name'] = $region_list[$order_info['city']]['name'] ? $region_list[$order_info['city']]['name'] : '北京市';
                $shop_up['area_name'] = $region_list[$order_info['district']]['name']?$region_list[$order_info['district']]['name'] : '东城区';
                $shop_up['station_address'] = $order_info['address'] ? $order_info['address'] : '区驻地';
                $shop_up['lng'] = $order_info['receiver_lng'];
                $shop_up['lat'] = $order_info['receiver_lat'];
                $shop_up['contact_name'] = $order_info['consignee'];
                $shop_up['phone'] = $order_info['mobile'];

                $shopAddApi['url'] = "/api/shop/update";
                $shopAddApi['businessParams'] = json_encode($shop_up);

                $dada_client = new DadaRequestClient($config, $shopAddApi);
                $resp = $dada_client->makeRequest();
                $resp = object_array($resp);
                if($resp['status'] == 'success'){
                    //M('shop')->where(array('id'=>6))->setField('origin_shop_id', $origin_shop_id);
                }else{
                    return array('status'=>0, 'msg'=>'门店更新失败：'.$resp['msg'], 'result'=>'');
                    //$this->returnInfo(0, '门店注册失败：'.$resp['msg']);
                }
            }


            $receiver_address = $shop_info['city_name'].$shop_info['area_name'].
                $shop_info['shop_address_street'];
            $receiver_name = $shop_info['shop_user'];
            $receiver_lat = $shop_info['latitude'];
            $receiver_lng = $shop_info['longitude'];
            $receiver_phone = $shop_info['shop_tel'];
            $order_sn = 'R'.$order_info['order_sn'];
        }

        $orderModel['shop_no'] = $origin_shop_id;	// 第三方门店编号

        $orderModel['origin_id'] = $order_sn;//'R'.$order_info['order_sn'];			// 第三方订单号
        $orderModel['city_code'] = $city_code ;						// 城市code(可以参照城市code接口)
        $orderModel['cargo_price'] = $order_info['order_amount'];
        $orderModel['is_prepay'] = 0;
        $orderModel['receiver_name'] = $receiver_name;
        $orderModel['receiver_address'] = $receiver_address;
        $orderModel['receiver_lat'] = $receiver_lat;
        $orderModel['receiver_lng'] = $receiver_lng;
        $orderModel['receiver_phone'] = $receiver_phone;
        $orderModel['callback'] = parseMediaUrl('/index.php/Shop/Order/dd_callback');							// 回调url, 每次订单状态变更会通知该url(参照回调接口)

//*********************3.实例化一个api*************************
        $addOrderApi = new AddOrderApi(json_encode($orderModel));
        $addOrderData['url'] = "/api/order/queryDeliverFee";
        $addOrderData['businessParams'] = json_encode($orderModel);

//***********************4.实例化客户端请求************************

        $dada_client = new DadaRequestClient($config, $addOrderData);
        $resp = $dada_client->makeRequest();
        $resp = object_array($resp);
        if($resp['status'] == 'success'){
            //$update['shipping_price_real'] = $resp['result']['fee'];
            //$update['exp_fee_rate'] = tpCache('shopping.dd_exp_fee_rate');
            //M('order')->where(array('order_id'=>$order_id))->save($update);
            //$this->orderActionLog($order_id,'商家发货');
            return array('status'=>1, 'msg'=>$resp['msg'], 'result'=>$resp['result']);
            //$this->returnInfo(1, $resp['msg'], $resp['result']);
        }else{
            return array('status'=>0, 'msg'=>$resp['msg'], 'result'=>$resp['code']);
            //$this->returnInfo(0, $resp['msg'], $resp['code']);
        }
    }
    //具体dada发货
    private function after_query_detail($order_info = null, $deliveryNo=''){
        if(!$order_info){
            return array('status'=>0, 'msg'=>'订单信息有误', 'result'=>'');
        }

        if(!$deliveryNo){
            return array('status'=>0, 'msg'=>'未传递单号', 'result'=>'');
        }

        $app_key = tpCache('shopping.dd_app_key');
        $app_secret = tpCache('shopping.dd_app_secret');
        $source_id = tpCache('shopping.dd_source_id');
        $is_test_dada= tpCache('shopping.dd_is_test');

        if(!$app_key || !$app_secret ||!$source_id){
            return array('status'=>0, 'msg'=>'系统参数异常', 'result'=>'');
            //$this->returnInfo(0, '系统参数异常');
        }

        $config['app_key'] = $app_key;
        $config['app_secret'] = $app_secret;
        $config['v'] = '1.0';
        $config['format'] = 'json';
        $config['source_id'] = $is_test_dada == 1 ? '73753' : $source_id;
        $config['host'] = $is_test_dada == 1 ?  'http://newopen.qa.imdada.cn' : "https://newopen.imdada.cn";


        //$shop_info = M('shop')->where(array('id'=>$order_info['shop_id']))->find();
        //无门店数据

        $orderModel['deliveryNo'] = $deliveryNo;
//*********************3.实例化一个api*************************
        //$addOrderApi = new AddOrderApi(json_encode($orderModel));
        $addOrderData['url'] = "/api/order/addAfterQuery";
        $addOrderData['businessParams'] = json_encode($orderModel);

//***********************4.实例化客户端请求************************

        $dada_client = new DadaRequestClient($config, $addOrderData);
        $resp = $dada_client->makeRequest();
        $resp = object_array($resp);
        if($resp['status'] == 'success'){
            return array('status'=>1, 'msg'=>$resp['msg'], 'result'=>$resp['result']);
            //$this->returnInfo(1, $resp['msg'], $resp['result']);
        }else{
            return array('status'=>0, 'msg'=>$resp['msg'], 'result'=>$resp['code']);
            //$this->returnInfo(0, $resp['msg'], $resp['code']);
        }
    }
    /**
     * 获取达达城市列表
     */
    public function get_dd_citycode(){
        $app_key = tpCache('shopping.dd_app_key');
        $app_secret = tpCache('shopping.dd_app_secret');
        $source_id = tpCache('shopping.dd_source_id');
        $is_test_dada= tpCache('shopping.dd_is_test');

        if(!$app_key || !$app_secret ||!$source_id){
            $this->returnInfo(0, '系统参数异常');
        }

        $config['app_key'] = $app_key;
        $config['app_secret'] = $app_secret;
        $config['v'] = '1.0';
        $config['format'] = 'json';
        $config['source_id'] = $is_test_dada == 1 ? '73753' : $source_id;
        $config['host'] = $is_test_dada == 1 ?  'http://newopen.qa.imdada.cn' : "https://newopen.imdada.cn";
        $config['body'] = '';
        //$cityCodeApi = new CityCodeApi('');
        $cityCodeApi['url'] = "/api/cityCode/list";
        $cityCodeApi['businessParams'] = json_encode('');

//***********************4.实例化客户端请求************************
        $dada_client = new DadaRequestClient($config, $cityCodeApi);
        $resp = $dada_client->makeRequest();
        $resp = (array)$resp;
        if($resp['status'] == 'success'){
            $this->returnInfo(1, '达达城市列表数据', $resp['result']);
        }else{
            $this->returnInfo(0, $resp['msg']);
        }
    }

    /**
     * 达达发货回调方法
     */
    public function dd_callback(){
        $order_id = I('order_id', '', 'trim');
        $order_info = M('order')->where(array('order_sn'=>$order_id))->find();
        if(!$order_info || $order_info['shipping_status'] != 1 || $order_info['order_status'] == 0 || $order_info['shipping_code'] != 'dada'){
            $this->returnInfo(0, '订单信息有误');
        }
        $order_status = I('order_status', 1, 'intval');
        //已完成
        if($order_status == 4 && $order_info['order_status'] != 2){
            $update_data['order_status'] = 2;
            $update_data['confirm_time'] = I('update_time');
            M('order')->where(array('order_id'=>$order_info['order_id']))->save($update_data);
            $this->orderActionLog($order_info['order_id'],'用户签收');
            //修改商铺 金额
            //accountLogShop($order_info['shop_id'], $order_info['total_amount'], '入账', 1, 0, 0, $order_info['order_id'], $order_id );

        }else if(in_array($order_status, array(5, 7, 1000)) && $order_info['shipping_status'] != 0){
            $update_data['shipping_status'] = 0;
            $update_data['shipping_time'] = 0;
            M('order')->where(array('order_id'=>$order_info['order_id']))->save($update_data);
            $this->orderActionLog($order_info['order_id'],'发货异常');
        }

    }

    /**
     * 允许退款审核
     */
    public function confirm_drawback(){
        $order_id = I('order_id', 0, 'intval');
        //$id = I('id', 0, 'intval');
        $need_exp = I('need_exp', 0, 'intval');
        $status = I('status', 1, 'intval');

        $orderModel = M('order');
        $order_info = $orderModel->where(array('order_id'=>$order_id, 'shop_id'=>$this->shop_info['shop_id']))->find();

        if(!$order_info){
            $this->returnInfo(0, '订单信息有误');
        }
        if($order_info['is_drawback'] != 1){
            $this->returnInfo(0, '无待处理退款申请');
        }

        $drawbackModel = M('drawback');
        $drawback_where['order_id'] = $order_id;
        $drawback_where['status'] = 0;
        /*if($id > 0){
            $drawback_where['id'] = $id;
        }*/
        //$count_deal = 0;
        //$count_white_deal = $drawbackModel->where(array('order_id'=>$order_id, 'status'=>0))->count();
        $drawback_info = $drawbackModel->where($drawback_where)->find();

        if(!$drawback_info){
            $this->returnInfo(0,'暂无待处理申请退款信息');
        }

        //M()->startTrans();

        //$money_amount = 0;
        //$rec_id = array();
        //foreach($drawback_list as $val){
            //if($drawback_info['status'] == 0){
        //1允许退款 2.退款驳回
        if(!in_array($status, array(1, 2))){
            $this->returnInfo(0,'审核状态信息有误');
        }

        M()->startTrans();
                $update_drawback['status'] = $status;
                if($status == 1){
                    if($need_exp == 1){
                        if($drawback_info['shop_goods_type'] == 0){
                            $query_info = $this->query_fee_detail($order_info, '',1);
                            if($query_info['status'] == 1){
                                $exp_fee = $query_info['result']['fee'];
                            }else{
                                $this->returnInfo(0,$query_info['msg']);
                            }
                            $after_query_info = $this->after_query_detail($order_info, $query_info['result']['deliveryNo']);
                            if($after_query_info['status'] == 1){
                                $exp_no = $query_info['result']['deliveryNo'];
                            }else{
                                $this->returnInfo(0,$after_query_info['msg']);
                            }
                            
                            $update_drawback['exp_fee'] = $exp_fee;
                            $update_drawback['exp_no'] = $exp_no;
                        }else{
                            $exp_fee = tpCache('shopping.drawback_exp_fee');
                            $update_drawback['exp_fee'] = $exp_fee;
                            $end_time = tpCache('shopping.drawback_exp_end_time');
                            $send_end_time = $end_time > 0 ? time() + $end_time * 24 *3600 : 0;
                            $update_drawback['send_time_end'] = $send_end_time;
                        }
                    }else{
                        $deal_drawback = $this->deal_drawback($drawback_info);
                        if($deal_drawback['status'] != 1){
                            M()->rollback();
                            $this->returnInfo(0, $deal_drawback['msg']);
                        }
                        $update_drawback['status'] = 4;
                        $update_drawback['exp_fee'] = 0;
                        $update_drawback['exp_no'] = '';

                        $update_drawback['finish_time'] = time();
                        $update_drawback['real_money'] = $drawback_info['money'];
                        $update_drawback['is_free_exp_fee'] = 0;
                    }
                    $update_drawback['need_exp'] = $need_exp;
                }else{

                    $deal_drawback = $this->deal_drawback($drawback_info, 0);
                    if($deal_drawback['status'] != 1){
                        M()->rollback();
                        $this->returnInfo(0, $deal_drawback['msg']);
                    }

                    $update_drawback['exp_fee'] = 0;
                    $update_drawback['exp_no'] = '';
                    $update_drawback['need_exp'] = 0;
                    $update_drawback['real_money'] = 0;
                    $update_drawback['reason'] = I('reason', '', 'trim');

                    $update_drawback['finish_time'] = time();
                    $update_drawback['is_free_exp_fee'] = 0;
                }
                $update_drawback['update_time'] = time();
                $update_drawback['auto_time'] = 0;
                $update_drawback['admin_id'] = $this->user_id;

                $update_drawback = $drawbackModel->where(array('id'=>$drawback_info['id']))->save($update_drawback);
                if($update_drawback === false){
                    M()->rollback();
                    $this->returnInfo(0, '操作退款申请失败');
                }

        M()->commit();
        $this->returnInfo(1, '操作成功');

    }

    /**
     * 完成退款申请
     */
    public function finish_drawback(){
        $order_id = I('order_id', 0, 'intval');
        if($order_id <= 0){
            $this->returnInfo(0, '订单参数有误');
        }
        $status = I('status', 4, 'intval');
        if(!in_array($status, array(4, 5))){
            $this->returnInfo(0, '状态参数有误');
        }
        $order_info = M('order')->where(array('order_id'=>$order_id))->find();
        if($order_info['is_drawback'] != 1){
            $this->returnInfo(0, '订单状态有误');
        }
        $drawbackModel = M('drawback');
        $drawback_info = $drawbackModel->where(array('order_id'=>$order_id))->find();
        if(!in_array($drawback_info['status'], array(1, 3))){
            $this->returnInfo(0, '退款申请状态有误');
        }

        if($status == 4){
            $allow_return = 1;
        }else{
            $allow_return = 0;
        }
        M()->startTrans();
        $deal_draw = $this->deal_drawback($drawback_info, $allow_return);
        if($deal_draw['status'] != 1){
            M()->rollback();
            $this->returnInfo(0, $deal_draw['msg']);
        }
        $update_draw['admin_id'] = $this->user_id;
        $money_amount = bcsub($drawback_info['money'], $drawback_info['exp_fee'], 2);
        $money_amount = $money_amount > 0 ? $money_amount : 0;

        $update_draw['real_money'] = $drawback_info['money'];//$money_amount;
        $update_draw['status'] = $status;
        $update_draw['finish_time'] = time();

        $is_success = $drawbackModel->where(array('order_id'=>$order_id))->save($update_draw);
        if($is_success === false){
            M()->rollback();
            $this->returnInfo(0, '申请退款信息操作失败');
        }

        M()->commit();
        $this->returnInfo(1, '操作成功');
    }

    /**
     * 确认退款
     */
    public function deal_drawback($drawback_info = null, $allow_return = 1){
        if(!$drawback_info){
            return array('status'=>0, 'msg'=>'申请退款信息有误');
        }

        if($allow_return == 1){
            $wallet_balance = M('shop')->where(array('id'=>$this->shop_info['shop_id']))->getField('wallet_balance');
            $money_amount = $drawback_info['money'];//bcsub($drawback_info['money'], $drawback_info['exp_fee'], 2);
            $money_amount = $money_amount > 0 ? $money_amount : 0;
            if($money_amount > $wallet_balance){
                return array('status'=>0, 'msg'=>'操作退款申请失败，店铺余额不足');
            }

            //user money
            if($money_amount > 0){
                //$is_success_log = accountLog($drawback_info['user_id'], $money_amount,  0, $desc = '申请退款', 0, $drawback_info['order_id'], '');

                $shop_wxpay = new WxpayController();
                $is_success_log = $shop_wxpay->drawback_pay($drawback_info['id']);

                if($is_success_log['status'] != 1){
                    return array('status'=>0, 'msg'=>'微信打款失败', 'result'=>$is_success_log['result']);
                }

                $shop_desc_money = $money_amount;
                $desc = '退款';

                $is_success_log_shop = accountLogShop($this->shop_info['shop_id'], 0 - $shop_desc_money, $desc, 0, 0, 0, $drawback_info['order_id'], '');
                if($is_success_log_shop['is_success'] === false){
                    return array('status'=>0, 'msg'=>'修改店铺余额失败');
                }

                if($drawback_info['need_exp'] == 1 && $drawback_info['is_free_exp_fee'] == 1){
                    $exp_money = $drawback_info['exp_fee'];
                    $desc_exp = '运费减免'.$drawback_info['exp_fee'].'元';
                    if($exp_money > 0){
                        $is_success_log_shop_exp = accountLogShop($this->shop_info['shop_id'], $exp_money, $desc_exp, 0, 0, 0, $drawback_info['order_id'], '');
                        if($is_success_log_shop_exp['is_success'] === false){
                            return array('status'=>0, 'msg'=>'修改店铺余额失败');
                        }
                    }

                }

                $this->orderActionLog($drawback_info['order_id'],'确认退款');
            }
        }

        //订单is_drawback
        $rec_id = explode(',', $drawback_info['order_goods_id']);
        $is_success_order = M('order_goods')->where(array('rec_id'=>array('in', $rec_id)))
            ->setField('apply_return', 2);
        if($is_success_order === false){
            return array('status'=>0, 'msg'=>'操作订单商品失败');
        }

        $update_order = M('order')->where(array('order_id'=>$drawback_info['order_id']))->setField('is_drawback', 2);
        if($update_order === false){
            return array('status'=>0, 'msg'=>'修改订单失败');
        }
        return array('status'=>1, '操作成功');
    }

    /**
     * 申请退款列表
     */
    public function get_drawback_list(){
        $order_id = I('order_id', 0, 'intval');
        if($order_id <= 0){
            $this->returnInfo(0, '订单参数有误');
        }

        $fields_dra = array('dra.id','dra.status', 'dra.create_time', 'dra.back_reason','dra.content',
            'dra.money','dra.real_money','dra.order_goods_id','dra.exp_fee','dra.need_exp',
            'dra.exp_no', 'dra.shop_goods_type', 'dra.create_time', 'dra.create_time', 'ord_g.goods_num',
            'ord_g.member_goods_price','goods.goods_name','goods.goods_id','goods.market_price','goods.goods_remark'
        ,'goods.original_img','ord.order_sn'
        );
        $drawbackModel = M('drawback');
        $count = $drawbackModel->alias('dra')
            ->field($fields_dra)
            ->join('ln_order_goods as ord_g ON dra.order_goods_id = ord_g.rec_id')
            ->join('ln_goods as goods ON ord_g.goods_id = goods.goods_id')
            ->join('ln_order as ord ON ord.order_id = dra.order_id')
            ->where(array('dra.order_id'=>$order_id))
            ->count();
        $p = I('p', 1, 'intval');
        $pagesize = I('pagesize', 10, 'intval');
        $drawback_list = $drawbackModel->alias('dra')
            ->field($fields_dra)
            ->join('ln_order_goods as ord_g ON dra.order_goods_id = ord_g.rec_id')
            ->join('ln_goods as goods ON ord_g.goods_id = goods.goods_id')
            ->join('ln_order as ord ON ord.order_id = dra.order_id')
            ->where(array('dra.order_id'=>$order_id))
            ->order('dra.id DESC')
            ->page($p, $pagesize)
            ->select();

        foreach($drawback_list as &$val){
            $val['original_img'] = parseMediaUrl($val['original_img']);
            $val['create_time_show'] = date('Y-m-d', $val['create_time']);
            $val['drawback_btn'] = $val['status'] == 0 ? 1 : 0;
            $val['status_str'] = draw_status_shop($val['status']);
        }
        $page_info = array('count'=>$count, 'page_count'=>count($drawback_list), 'p'=>I('p',1,'intval'), 'page_size'=>$pagesize);
        $this->returnInfo(1, '申请退款记录', array('page_info'=>$page_info, 'list'=>$drawback_list));
    }

    /*
     * 退款详情
     */
    public function get_drawback_info(){
        $order_id = I('order_id', 0, 'intval');
        if($order_id <= 0){
            $this->returnInfo(0,'订单信息有误');
        }
        $field = array('order_id', 'order_sn', 'is_drawback', 'order_amount');
        $order_info = M('order')->field($field)->where(array('order_id'=>$order_id, 'shop_id'=>$this->shop_info['shop_id']))->find();
        if(!$order_info){
            $this->returnInfo(-1,'订单信息有误');
        }
        $fields_dra = array('ord_g.rec_id', 'ord_g.goods_num',
            'ord_g.member_goods_price','goods.goods_name','goods.goods_id','goods.market_price','goods.goods_remark'
        ,'goods.original_img'
        );

        $drawback_list = M('drawback')->field('id, status, img, back_reason, content, money, exp_fee, exp_no, 
            create_time, order_goods_id')
            ->where(array('order_id'=>$order_id))->order('id DESC')->select();
        $orderGoodsModel = M('order_goods');
        $real_money = 0;
        foreach($drawback_list as &$val){
            if($val['img']){
                $img_array = unserialize($val['img']);
                foreach($img_array as &$img_val){
                    $img_val = parseMediaUrl($img_val);
                }
                $val['img'] = $img_array;
            }
            $val['order_sn'] = $order_info['order_sn'];
            $val['create_time_show'] = date('Y-m-d', $val['create_time']);
            $val['drawback_btn'] = $val['status'] == 0 ? 1 : 0;
            $val['status_str'] = draw_status_user($val['status']);
            $money_amount = bcsub($val['money'], $val['exp_fee'], 2);
            $val['real_amount'] = $money_amount > 0 ? $money_amount : 0;
            $order_goods_list = $orderGoodsModel->alias('ord_g')
                ->field($fields_dra)
                ->join('ln_goods as goods ON ord_g.goods_id = goods.goods_id', 'left')
                ->where(array('ord_g.rec_id' => array('in', explode(',', $val['order_goods_id']))))
                ->select();
            foreach($order_goods_list as &$val2){
                $val2['original_img'] = parseMediaUrl($val2['original_img']);
            }
            $val['order_goods'] = $order_goods_list;
            $real_money = bcadd($real_money, $val['real_amount'], 2);
        }
        $order_info['real_money'] = $real_money;
        $order_info['drawback_btn'] = $order_info['is_drawback'] == 1 ? 1 : 0;
        $order_info['drawback_list'] = $drawback_list;
        $this->returnInfo(1, '申请退款记录', $order_info);
    }

}